package selef.xiafan.service.impl;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import selef.xiafan.dao.*;
import selef.xiafan.entity.Customer;
import selef.xiafan.entity.order.Order;
import selef.xiafan.entity.order.OrderCustomer;
import selef.xiafan.entity.system.SysPermission;
import selef.xiafan.entity.user.User;
import selef.xiafan.query.CustomerQuery;
import selef.xiafan.service.ICustomerService;
import selef.xiafan.util.result.PageResult;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ICustomerServiceImpl implements ICustomerService {
    @Autowired
    CustomerDao customerDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    OrderCustomerDao orderCustomerDao;
    @Autowired
    UserDao userDao;
    @Autowired
    SysPermissionDao sysPermissionDao;
    @Autowired
    ISysPermissionServiceImpl iSysPermissionS;

    /*
     * 查询所有如果使用new Sort，会提示new Sort已经被私有化，无法使用new Sort(Sort.Direction.DESC,properties)
     * */
    @Override
    public List<Customer> getAll() {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        return customerDao.findAll(sort);
    }

    @Override
    public PageResult<Customer> getReturnList(CustomerQuery customerQuery) {
        Integer page = (customerQuery.getPage() - 1) * customerQuery.getSize();
        Integer size = customerQuery.getSize();
        Long total = orderDao.countFinalList();
        if (total != 0L) {
            List<Order> orderInReturn = orderDao.findAllByPageQuery(page, size);
            List<Order> orderList = new ArrayList<>();
            // 根据订单好查询客户id
            for (Order order : orderInReturn) {
                Integer customerId = orderCustomerDao.findByOrderId(order.getOrderId()).getCustomerId();
                // 根据客户id查询客户信息
                Customer customer = customerDao.findById(customerId).get();
                customer.setAddress(order.getAddress());
                order.setCustomer(customer);
                // 处理两个非空字段
                order.setCreateBy(order.getCreateBy());
                order.setCreateTime(order.getCreateTime());
                orderList.add(order);
            }
            return new PageResult<>(total, orderList);
        }
        return new PageResult<>();
    }

    /*
     * 客户注册：
     * 1客户表中没有信息，用户表中有信息
     * 2客户表中没有信息，用户表中有信息时
     * 3客户表没有信息，用户表没有信息
     * */
    @Override
    public Integer register(Customer requestCustomer) throws ParseException {
        // 根据手机号查询客户表
        List<Customer> customerInDB = customerDao.findAllByPhone(requestCustomer.getPhone());
        User user = new User();
        if (customerInDB.size() == 0) { // 客户表中没有数据
            user.setUsername(requestCustomer.getPhone());
            user.setRealName(requestCustomer.getName());
            user.setPhone(requestCustomer.getPhone());
            Date simpDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            user.setCreateTime(simpDate);
            user.setEnable(true);
            user.setGender("1");
            user.setIsSys(false); // 非系统登录人员

            String salt = new SecureRandomNumberGenerator().nextBytes().toString();
            int times = 2;
            // 对密码加密
            String encodedPassword = new SimpleHash("md5", requestCustomer.getPassword(), salt, times).toString();
            user.setSalt(salt);
            user.setPassword(encodedPassword);
            userDao.save(user);

            customerDao.save(requestCustomer);
            return 1;
        } else {
            return 2; // 该手机号已被注册
            /*for (Customer customer : customerInDB) {
                if (requestCustomer.getPhone().equals(customer.getPhone())) {
                    return 2;
                } else {
                    user.setUsername(requestCustomer.getPhone());
                    user.setRealName(requestCustomer.getName());
                    user.setPhone(requestCustomer.getPhone());
                    Date simpDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    user.setCreateTime(simpDate);
                    user.setEnable(true);
                    user.setGender("1");

                    String salt = new SecureRandomNumberGenerator().nextBytes().toString();
                    int times = 2;
                    // 对密码加密
                    String encodedPassword = new SimpleHash("md5", requestCustomer.getPassword(), salt, times).toString();
                    user.setSalt(salt);
                    user.setPassword(encodedPassword);
                    userDao.save(user);

                    customerDao.save(requestCustomer);
                    return 1;
                }
            }*/
        }
    }

    @Override
    public List<SysPermission> getCustomerMenus() {
        String url = "/customer";
        Integer permissionId = sysPermissionDao.findByUrl(url).getId();
        List<SysPermission> listPermissionMenu = sysPermissionDao.findAllById(permissionId)
                .stream().distinct().collect(Collectors.toList());
        iSysPermissionS.handlePermission(listPermissionMenu);
        return listPermissionMenu;
        /*Class<?> clazz;
        try {
            clazz = Class.forName("ISysPermissionSImpl");
            Method method = clazz.getMethod("handlePermission", List.class);
            Object object = method.invoke(clazz.newInstance(), listPermissionMenu);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }*/
    }

    @Override
    public PageResult getCustomerList(CustomerQuery customerQuery) {
        Integer page = (customerQuery.getPage() - 1) * customerQuery.getSize();
        Integer size = customerQuery.getSize();

        Long total = customerDao.countNoQuery();
        if (total != 0L) {
            List<Customer> customerList = customerDao.findAllNoQuery(page, size);
            // 查询顾客总消费金额

            for (Customer customer : customerList) { // 查询用户
                BigDecimal consumptionAmount = new BigDecimal(0);
                // 查询用户与订单中间表找到订单信息
                List<String> orderId = orderCustomerDao.findAllByCustomerId(customer.getId())
                        .stream().map(OrderCustomer::getOrderId).collect(Collectors.toList());
                if (orderId.size() != 0) { // 中间表有信息时
                    List<Order> orderList = orderDao.findAllByOrderIdIn(orderId)
                            .stream().distinct().collect(Collectors.toList()); // 根据用户关联的订单id查询信息
                    if (orderList.size() != 0) {
                        for (Order order : orderList) {
                            BigDecimal orderPrice = order.getTotalPrice();
                            if (orderPrice == null) {
                                orderPrice = new BigDecimal(0);
                            }
                            consumptionAmount = orderPrice.add(consumptionAmount);
                        }
                    }
                }
                customer.setConsumptionTotal(consumptionAmount);
            }
            return new PageResult(total, customerList);
        } else {
            return new PageResult();
        }
    }

    @Override
    public Integer changeVip(Customer customer) {
        String phone = customer.getPhone();
        List<Customer> allByPhone = customerDao.findAllByPhone(phone);
        if (customer.getIsVip()) { // 升级为Vip身份
            customerDao.save(customer);
            for (Customer customer1 : allByPhone) {
                if (phone != null && phone.equals(customer1.getPhone())) {
                    customer1.setIsVip(customer.getIsVip());
                    customerDao.save(customer1);
                }
            }
            return 1;
        } else { // 取消Vip身份
            customerDao.save(customer);
            for (Customer customer1 : allByPhone) {
                if (phone != null && phone.equals(customer1.getPhone())) {
                    customer1.setIsVip(customer.getIsVip());
                    customerDao.save(customer1);
                }
            }
            return 2;
        }
    }

    @Override
    public Integer AddUpdate(Customer customer) {
        if (customer.getId() == null) {
            customer.setIsVip(false);
            customerDao.save(customer);
            return 1;
        } else {
            customerDao.save(customer);
            return 2;
        }
    }

    @Override
    public void changePass(User requestUser) {
        User UserInDbByUsername = userDao.findByUsername(requestUser.getUsername());// 根据客户的手机号（登录账号进行查询--手机号唯一）
        String password = requestUser.getPassword();

        // 默认生成16位盐 先生成随机byte数组，再转成字符串类型的base64并返回
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        int times = 2;
        // 对密码加密
        String encodedPassword = new SimpleHash("md5", password, salt, times).toString();
        UserInDbByUsername.setSalt(salt);
        UserInDbByUsername.setPassword(encodedPassword);

        userDao.save(UserInDbByUsername);
    }
}
